﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using web_api.Entities;
using web_api.Helpers;
using web_api.Models;
using web_api.Services;

namespace web_api.Controllers {
  [ApiController]
  [Route("api/companyCollections")]
  public class companyCollectionsController : ControllerBase {
    private readonly IMapper mapper;
    private readonly ICompanyRepository companyRepository;

    public companyCollectionsController(IMapper mapper, ICompanyRepository companyRepository) {
      this.mapper = mapper;
      this.companyRepository = companyRepository;
    }
    [HttpGet("{ids}", Name = nameof(GetCompanyCollection))]
    //key1,key2
    public async Task<IActionResult> GetCompanyCollection([FromRoute][ModelBinder(BinderType = typeof(ArrayModelBinder))] IEnumerable<Guid> ids) {
      if (ids == null) {
        return BadRequest();
      }
      var entities = await companyRepository.GetCompaniesAsync(ids);
      if (ids.Count() != entities.Count()) {
        return NotFound();
      }
      var dtoToReturn = mapper.Map<IEnumerable<CompanyDto>>(entities);
      return Ok(dtoToReturn);
    }
    [HttpPost]
    //[Route]
    public async Task<ActionResult<IEnumerable<CompanyDto>>>
     GreateCompanyCollection(IEnumerable<CompanyAddDto> companyCollection) {
      var companyEntites = mapper.Map<IEnumerable<Company>>(companyCollection);
      foreach (var company in companyEntites) {
        companyRepository.AddCompany(company);
      }
      await companyRepository.SaveAsync();
      var dtosToReturn = mapper.Map<IEnumerable<CompanyDto>>(companyEntites);
      var idsString = string.Join(",", dtosToReturn.Select(x => x.Id));
      return CreatedAtAction(nameof(GetCompanyCollection), new { ids = idsString } ,dtosToReturn);
    }
  }
}
